<template>
    <div class="add-product-container">
        <h1 style="margin: 0px 0px 40px 80px;">添加商品</h1>

        <form @submit.prevent="submitForm" class="product-form">
            <!-- 一级分类 -->
            <div class="form-group">
                <label>一级分类</label>
                <select v-model="formData.categoryLevel1" @change="handleCategoryChange(1)">
                    <option value="">请选择</option>
                    <option v-for="cat in categoryLevel1List" :key="cat.id" :value="cat.id">{{ cat.name }}</option>
                </select>
            </div>

            <!-- 二级分类 -->
            <div class="form-group">
                <label>二级分类</label>
                <select v-model="formData.categoryLevel2" @change="handleCategoryChange(2)"
                    :disabled="!formData.categoryLevel1">
                    <option value="">请选择</option>
                    <option v-for="cat in categoryLevel2List" :key="cat.id" :value="cat.id">{{ cat.name }}</option>
                </select>
            </div>

            <!-- 三级分类 -->
            <div class="form-group">
                <label>三级分类</label>
                <select v-model="formData.categoryLevel3" :disabled="!formData.categoryLevel2">
                    <option value="">请选择</option>
                    <option v-for="cat in categoryLevel3List" :key="cat.id" :value="cat.id">{{ cat.name }}</option>
                </select>
            </div>

            <!-- 商品名称 -->
            <div class="form-group">
                <label>商品名称</label>
                <input type="text" v-model="formData.name" required placeholder="请输入商品名称" @blur="checkNameDuplicate" />
                <div v-if="nameError">{{ nameError }}</div>
            </div>

            <!-- 商品图片 -->
            <div class="form-group">
                <label>商品图片</label>
                <div class="file-upload">
                    <input type="file" @change="handleFileChange" accept="image/*" />
                    <div class="upload-preview" v-if="previewUrl">
                        <img :src="previewUrl" alt="预览" width="60" height="60" />
                    </div>
                    <div class="upload-text">
                        <span v-if="fileName">已选择: {{ fileName }}</span>
                        <span v-else>选择文件</span>
                    </div>
                </div>
            </div>

            <!-- 单价 -->
            <div class="form-group">
                <label>单价</label>
                <input type="number" v-model.number="formData.price" step="0.01" min="0" placeholder="请输入单价" />
            </div>

            <!-- 库存 -->
            <div class="form-group">
                <label>库存</label>
                <input type="number" v-model.number="formData.stock" min="0" placeholder="请输入库存数量" />
            </div>

            <!-- 描述 -->
            <div class="form-group">
                <label>描述</label>
                <textarea v-model="formData.description" placeholder="请输入商品描述"></textarea>
            </div>

            <!-- 提交按钮 -->
            <div class="form-actions">
                <button type="submit" class="btn-submit">提交</button>
                <button type="button" class="btn-cancel" @click="resetForm">取消</button>
            </div>
        </form>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import axios from 'axios'

// 表单数据
const formData = reactive({
    categoryLevel1: '',
    categoryLevel2: '',
    categoryLevel3: '',
    name: '',
    price: 0,
    stock: 0,
    description: '',
    file: null
})

const previewUrl = ref('')
const fileName = ref('')

const nameError = ref('')

const categoryLevel1List = ref([])
const categoryLevel2List = ref([])
const categoryLevel3List = ref([])

// 获取一级分类
const fetchCategoryLevel1 = async () => { 
    const response = await axios.get('/api/selectCategory1')
    categoryLevel1List.value = response.data.pc1List || []
    console.log("111", response.data.pc1List);
    if (!response.data.pc1List) {
        console.error('获取一级分类失败')
    }
}

// 根据一级分类获取二级分类
const fetchCategoryLevel2 = async (level1Id) => {
    if (!level1Id) return
    const response = await axios.get('/api/selectCategory2', {
        params: { parentId: level1Id }
    })
    categoryLevel2List.value = response.data.pc2List || []
}

// 根据二级分类获取三级分类
const fetchCategoryLevel3 = async (level2Id) => {
    if (!level2Id) return
    const response = await axios.get('/api/selectCategory3', {
        params: { parentId: level2Id }
    })
    categoryLevel3List.value = response.data.pc3List || []  
}

// 处理分类选择变化
const handleCategoryChange = async (level) => {
    if (level === 1) {
        formData.categoryLevel2 = ''
        formData.categoryLevel3 = ''
        categoryLevel2List.value = []
        categoryLevel3List.value = []

        await fetchCategoryLevel2(formData.categoryLevel1)
    } else if (level === 2) {
        formData.categoryLevel3 = ''
        categoryLevel3List.value = []

        await fetchCategoryLevel3(formData.categoryLevel2)
    }
}

// 处理文件选择
const handleFileChange = (event) => {
    const file = event.target.files[0]
    if (file) {
        formData.file = file
        fileName.value = file.name

        // 预览图
        const reader = new FileReader()
        reader.onload = (e) => {
            previewUrl.value = e.target.result
        }
        reader.readAsDataURL(file)
    }
}

// 检查商品名称是否重复
const checkNameDuplicate = async () => {
    if (!formData.name.trim()) {
        nameError.value = ''
        return
    }

    const response = await axios.get('/api/judgeProductName', {
        params: { name: formData.name }
    })

    if (response.data.code === 5500) {
        nameError.value = '商品名称已存在，请选择其他名称'
    } else {
        nameError.value = ''
    }
}
// 提交表单
const submitForm = async () => {
    // 验证表单
    if (!formData.name.trim()) {
        alert('商品名称不能为空')
        return
    }

    if (!formData.categoryLevel1) {
        alert('请先选择一级分类')
        return
    }

    if (nameError.value) {
        alert(nameError.value)
        return
    }

    const formDataToSend = new FormData()

    formDataToSend.append('name', formData.name)
    formDataToSend.append('categoryLevel1Id', formData.categoryLevel1)
    formDataToSend.append('categoryLevel2Id', formData.categoryLevel2)
    formDataToSend.append('categoryLevel3Id', formData.categoryLevel3)
    formDataToSend.append('price', formData.price)
    formDataToSend.append('stock', formData.stock)
    formDataToSend.append('description', formData.description)

    if (formData.file) {
        formDataToSend.append('myFile', formData.file)
    }

    const response = await axios.post('/api/addProduct', formDataToSend, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })

    if (response.data.code === 5200) {
        alert('商品添加成功')
        resetForm()
    } else {
        alert('添加失败: ' + response.data.error)
    }
}

// 重置表单
const resetForm = () => {
    Object.assign(formData, {
        categoryLevel1: '',
        categoryLevel2: '',
        categoryLevel3: '',
        name: '',
        price: 0,
        stock: 0,
        description: '',
        file: null
    })
    previewUrl.value = ''
    fileName.value = ''
    categoryLevel2List.value = []
    categoryLevel3List.value = []
}

onMounted(() => {
    fetchCategoryLevel1()
})
</script>

<style scoped>
.add-product-container {
    max-width: 500px;
    margin: 0 auto;
    padding: 20px;
}

.product-form {
    background-color: #fff;
    padding: 20px;
}

.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: bold;
    color: #333;
}

.form-group select,
.form-group input[type="text"],
.form-group input[type="number"],
.form-group textarea {
    width: 100%;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    box-sizing: border-box;
}

.form-group textarea {
    height: 100px;
    resize: vertical;
}

.required {
    color: red;
    margin-left: 5px;
}

.file-upload {
    position: relative;
    display: flex;
    align-items: center;
    gap: 10px;
}

.file-upload input[type="file"] {
    opacity: 0;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    cursor: pointer;
}

.upload-preview {
    width: 60px;
    height: 60px;
    border: 1px solid #ddd;
    border-radius: 4px;
    overflow: hidden;
}

.upload-preview img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.upload-text {
    flex: 1;
    padding: 10px;
    border: 1px dashed #ddd;
    border-radius: 4px;
    text-align: center;
    cursor: pointer;
    transition: background-color 0.3s;
}

.upload-text:hover {
    background-color: #f5f5f5;
}

.form-actions {
    display: flex;
    gap: 10px;
    justify-content: flex-end;
    margin-top: 30px;
}

.btn-submit,
.btn-cancel {
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 16px;
}

.btn-submit {
    background-color: #007bff;
    color: white;
}
</style>